package com.czkt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lqm
 * @ClassName LoginController
 * @description: TODO
 */
@Controller
public class LoginController {



    @RequestMapping("/user/login")
    public String login(HttpServletRequest request) {
        return "login";
    }

    @Autowired
    AuthenticationManager authenticationManager;
    /**
     * 自定义登录
     *
     * @param userName
     * @param pwd
     * @return
     */
    @RequestMapping("/user/dologin")
    @ResponseBody
    public Object dologin(String userName, String pwd, Model model) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, pwd);
        //把当前需要认证的用户给security
        Authentication authentication = authenticationManager.authenticate(token);

        Map<String ,Object> resultMap =new HashMap<>();
        if (authentication == null) {
            model.addAttribute("errMsg", "账号和密码错误！");
            resultMap.put("state",-1);
        } else {
            // 将认证信息保存在会话中
            SecurityContextHolder.getContext().setAuthentication(authentication);
            resultMap.put("state",0);
        }
        return  resultMap;
    }

    @RequestMapping("/user/list")
    @ResponseBody
//    @PreAuthorize("hasAnyAuthority('admin')")
    public String index(String token) {

        return "index";
    }


    @RequestMapping("/user/index2")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('admin2')")
    public String index2(HttpServletRequest request) {
        return "index2";
    }
}
